package org.fuxian.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.fuxian.common.Constraints;
import org.fuxian.domain.MyHouse;
import org.fuxian.service.IMyHouseService;
import org.fuxian.util.AliyunOssUtil;
import org.fuxian.util.FileResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/house")
public class MyHouseController {

    @Autowired
    IMyHouseService myHouseService;


    @RequestMapping("/findAllHousePD")
    @ResponseBody
    public Object findAllHousePD(int current, Integer flag) {
        PageHelper.startPage(current, Constraints.PAGE_SIZE);
        List<MyHouse> list = myHouseService.findAll(flag);
        return new PageInfo(list);
    }

    @RequestMapping("/addHouse")
    @ResponseBody
    public String addHouse(MyHouse myHouse, HttpServletRequest req) {

        String realPath = req.getSession().getServletContext().getRealPath("/upload");
        MultipartHttpServletRequest mf;
        mf = (MultipartHttpServletRequest) req;
        CommonsMultipartFile file1 = (CommonsMultipartFile) mf.getFile("file1");
        CommonsMultipartFile file2 = (CommonsMultipartFile) mf.getFile("file2");
        CommonsMultipartFile file3 = (CommonsMultipartFile) mf.getFile("file3");
        List<MultipartFile> files = new ArrayList<>();
        files.add(file1);
        files.add(file2);
        files.add(file3);

        FileResult fileResult = AliyunOssUtil.upload(files);
        String himg = fileResult.getFileAPUrl();
        System.out.println("###############add" + himg);
        if (himg.length() > 0) {
            myHouse.setHimg(himg);
        }
        myHouse.setHflag(0);
        int count = myHouseService.insert(myHouse);
        return count + "";
    }


    @RequestMapping("/findHouseById")
    @ResponseBody
    public Object findHouseById(Integer hid) {
        return myHouseService.findById(hid);
    }

    @RequestMapping("/uppHouse")
    @ResponseBody
    public String uppHouse(MyHouse myHouse, HttpServletRequest req) {

        String realPath = req.getSession().getServletContext().getRealPath("/upload");
        MultipartHttpServletRequest mf;
        mf = (MultipartHttpServletRequest) req;
        CommonsMultipartFile file1 = (CommonsMultipartFile) mf.getFile("file1");
        CommonsMultipartFile file2 = (CommonsMultipartFile) mf.getFile("file2");
        CommonsMultipartFile file3 = (CommonsMultipartFile) mf.getFile("file3");

        /*
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String ds = format.format(date);

        String filePath = realPath + File.separator + ds;
        File realDir = new File(filePath);
        if (!realDir.exists()) {
            realDir.mkdirs();
        }

        StringBuffer himg = new StringBuffer();
        if (file1.getSize() != 0) {
            himg.append(ds);
            himg.append(File.separator);
            himg.append(getFileName(file1, filePath));
            himg.append(Constraints.FILE_FLAG);
        }
        if (file2.getSize() != 0) {
            himg.append(ds);
            himg.append(File.separator);
            himg.append(getFileName(file2, filePath));
            himg.append(Constraints.FILE_FLAG);
        }
        if (file3.getSize() != 0) {
            himg.append(ds);
            himg.append(File.separator);
            himg.append(getFileName(file3, filePath));
        }

        if (himg.length() > 0) {
            //删除之前图片
            MyHouse house = myHouseService.findById(myHouse.getHid());
            if (house.getHimg() != null && !"".equals(house.getHimg()))
                delImg(realPath, house.getHimg());
            myHouse.setHimg(himg.toString());
        }
        */

        List<MultipartFile> files = new ArrayList<>();
        files.add(file1);
        files.add(file2);
        files.add(file3);

        FileResult fileResult = AliyunOssUtil.upload(files);
        String himg = fileResult.getFileAPUrl();
        System.out.println("###############update" + himg);
        if (himg.length() > 0) {
            myHouse.setHimg(himg);
        }

        int count = myHouseService.update(myHouse);
        return count + "";
    }


    @RequestMapping("/look")
    @ResponseBody
    public Object look(Integer hid) {
        return myHouseService.findById(hid);
    }

    /**
     * 下架
     *
     * @param hid
     * @return
     */
    @RequestMapping("/down")
    @ResponseBody
    public String down(Integer hid) {
        int count = myHouseService.down(hid);
        return count + "";
    }

    /**
     * 上架
     *
     * @param hid
     * @return
     */
    @RequestMapping("/up")
    @ResponseBody
    public String up(Integer hid) {
        int count = myHouseService.up(hid);
        return count + "";
    }


    /**
     * 更新前删除图片
     *
     * @param realPath
     * @param himg
     */
    private void delImg(String realPath, String himg) {
        String[] fileNames = himg.split(Constraints.FILE_FLAG);
        for (String fileName : fileNames) {
            File file = new File(realPath + File.separator + fileName);
            file.delete();
        }

    }


    /**
     * 将文件保存在项目中并返回文件名称
     *
     * @param file
     * @param filePath
     * @return
     */
    private String getFileName(CommonsMultipartFile file, String filePath) {
        String filename = UUID.randomUUID().toString().replaceAll("-", "") +
                file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(
                        "."));

        String path = filePath + File.separator + filename;

        File f1 = new File(path);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), f1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }
}
